package com.woniu.config;

import com.woniu.common.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @Author LXB
 * @Date 2023/8/19 20:21
 * @Description
 **/
@ConditionalOnMissingClass("org.springframework.cloud.gateway.config.GatewayAutoConfiguration")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Slf4j
@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response
    ) {
        String uri = request.getURI().toString();
        if (
                uri.contains("/v2/api-docs")
                || uri.contains("/swagger-resources")
                || uri.contains("/swagger-ui.html")
                || uri.contains("/actuator")
                || uri.contains("/error")
        ) {
            return body;
        }
        if (body instanceof byte[]) {
            return body;
        }
        ResponseInfo result;
        if (Objects.isNull(body)) {
            result = ResponseInfo.ok(null);
        }
//        else if (body instanceof String){
//
//            if (((String) body).contains("<xml>")){
//                return body;
//            }
//
//            result = ResponseInfo.ok(body);
//        }
        else if (body instanceof ResponseInfo) {
            result = (ResponseInfo)body;
        } else {
            result = ResponseInfo.ok(body);
        }

        return result;
    }

}
